<template>
  <view>
    <view>
      <slot name="top"></slot>
    </view>
    <view
      class="ss-order-card-warp ss-flex ss-col-stretch ss-row-between bg-white"
      :style="[{ borderRadius: radius + 'rpx', marginBottom: marginBottom + 'rpx' }]"
    >
      <view class="img-box ss-m-r-24">
        <image class="order-img" :src="sheep.$url.cdn(img)" mode="aspectFill"></image>
      </view>
      <view
        class="box-right ss-flex-col ss-row-between"
        :style="[{ width: titleWidth ? titleWidth + 'rpx' : '' }]"
      >
        <view class="title-text ss-line-2" v-if="title">{{ title }}</view>
        <view v-if="skuString" class="spec-text ss-m-t-8 ss-m-b-12">{{ skuString }}</view>
        <view class="groupon-box">
          <slot name="groupon"></slot>
        </view>
        <view class="ss-flex" style="display: flex;justify-content: space-between">
          <view class="ss-flex ss-col-center">
            <view
              class="price-text ss-flex ss-col-center"
              :style="[{ color: priceColor }]"
              v-if="price && Number(price) > 0"
            >
              ￥{{ fen2yuan(price) }}
            </view>
            <view v-if="point && Number(price) > 0">+</view>
            <view class="price-text ss-flex ss-col-center" v-if="point">
              <image
                :src="sheep.$url.static('/static/img/shop/goods/score1.svg')"
                class="point-img"
              ></image>
              <view>{{ point }}</view>
            </view>
            <view v-if="num" class="total-text ss-flex ss-col-center">x {{ num }}</view>
            <slot name="priceSuffix"></slot>
          </view>
          <view v-if="dataInfo.isReservation && orderStatus!==0 && orderStatus!==40">
            <button v-if="dataInfo.reservationStatus==='NONE'"
                    class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                    @tap.stop="showReservationModal"
            >
              预约
            </button>
            <!-- 否则显示当前状态的中文描述 -->
            <view v-else class="order-state ss-font-26">
              {{ getReservationStatusText(dataInfo.reservationStatus) }}
            </view>
          </view>
        </view>
        <view class="tool-box">
          <slot name="tool"></slot>
        </view>
        <view>
          <slot name="rightBottom"></slot>
        </view>
      </view>
    </view>

    <!-- 预约弹窗 -->
    <view v-if="isReservationModalVisible" class="reservation-modal-overlay" @tap="hideReservationModal">
      <view class="reservation-modal" @tap.stop>
        <view class="modal-header">
          <view class="modal-title">预约信息</view>
          <view class="modal-close" @tap="hideReservationModal">×</view>
        </view>

        <view class="modal-content">
          <!-- 预约人选择 -->
          <view class="form-item">
            <view class="form-label">预约人</view>
            <picker
              mode="selector"
              :value="selectedUserIndex"
              :range="userDisplayList"
              @change="onUserChange"
              class="form-picker"
            >
              <view class="form-input picker-display">
                {{ selectedUserDisplay || '请选择预约人' }}
              </view>
            </picker>
          </view>

          <!-- 预约时间选择 -->
          <view class="form-item">
            <view class="form-label">预约时间</view>
            <picker
              mode="multiSelector"
              :value="dateTimeIndex"
              :range="dateTimeRange"
              @change="onDateTimeChange"
              class="form-picker"
            >
              <view class="form-input picker-display">
                {{ reservationForm.datetime || '请选择预约时间' }}
              </view>
            </picker>
          </view>

          <!-- 备注 -->
          <view class="form-item">
            <view class="form-label">备注</view>
            <textarea
              class="form-textarea"
              v-model="reservationForm.remark"
              placeholder="请输入备注信息（选填）"
              maxlength="200"
            ></textarea>
          </view>
        </view>

        <view class="modal-footer">
          <button class="cancel-btn" @tap="hideReservationModal">取消</button>
          <button class="confirm-btn" @tap="confirmReservation" :disabled="!canConfirm">确认预约</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import sheep from '@/sheep';
  import { computed, ref, reactive, onMounted } from 'vue';
  import { fen2yuan } from '@/sheep/hooks/useGoods';
  import CustomerApi from '@/sheep/api/customer/customer';
  import { WxaSubscribeTemplate } from '@/sheep/helper/const';

  /**
   * 订单卡片
   *
   * @property {String} img 											- 图片
   * @property {String} title 										- 标题
   * @property {Number} titleWidth = 0								- 标题宽度，默认0，单位rpx
   * @property {String} skuText 										- 规格
   * @property {String | Number} price 								- 价格
   * @property {String} priceColor 									- 价格颜色
   * @property {Number | String} num									- 数量
   *
   */
  const props = defineProps({
    img: {
      type: String,
      default: 'https://img1.baidu.com/it/u=1601695551,235775011&fm=26&fmt=auto',
    },
    dataInfo:{
      type: Object,
      default: {},
    },
    orderStatus:{
      type: Number,
      default: 0,
    },
    title: {
      type: String,
      default: '',
    },
    titleWidth: {
      type: Number,
      default: 0,
    },
    skuText: {
      type: [String, Array],
      default: '',
    },
    price: {
      type: [String, Number],
      default: '',
    },
    priceColor: {
      type: [String],
      default: '',
    },
    num: {
      type: [String, Number],
      default: 0,
    },
    point: {
      type: [String, Number],
      default: '',
    },
    radius: {
      type: [String],
      default: '',
    },
    marginBottom: {
      type: [String],
      default: '',
    },
  });

  // 定义事件
  const emit = defineEmits(['reservation-confirm']);

  // 预约弹窗相关状态
  const isReservationModalVisible = ref(false);

  // 用户列表相关
  const userList = ref([]);
  const selectedUserIndex = ref(0);
  const state = reactive({
    searchKeyword: ''
  });

  // 预约表单数据
  const reservationForm = reactive({
    customerId: '',
    customerName: '',
    contactPhone: '',
    datetime: '',
    remark: ''
  });

  // 日期时间选择器数据
  const dateTimeIndex = ref([0, 0]);
  const dateTimeRange = ref([[], []]);

  // 获取用户列表
  const getUserList = async () => {
    try {
      let { code, data } = await CustomerApi.getCustomerPage({
        pageNo: 1,
        pageSize: -1,
        customerName: state.searchKeyword || undefined,
      });

      if (code !== 0) {
        throw new Error('获取客户列表失败');
      }
      userList.value = data.list || [];

      // 自动选中第一个用户
      if (userList.value.length > 0) {
        setSelectedUser(0);
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
      uni.showToast({
        title: '获取客户列表失败',
        icon: 'none'
      });
    }
  };

  // 设置选中的用户
  const setSelectedUser = (index) => {
    if (userList.value.length > index && index >= 0) {
      selectedUserIndex.value = index;
      const selectedUser = userList.value[index];
      reservationForm.customerId = selectedUser.id;
      reservationForm.customerName = selectedUser.customerName;
      reservationForm.contactPhone = selectedUser.contactPhone || '';
    }
  };

  // 用户显示列表（姓名 + 电话）
  const userDisplayList = computed(() => {
    return userList.value.map(user => `${user.customerName} (${user.contactPhone || '无电话'})`);
  });

  // 当前选中用户的显示文本
  const selectedUserDisplay = computed(() => {
    if (userList.value.length > 0 && selectedUserIndex.value >= 0 && selectedUserIndex.value < userList.value.length) {
      const user = userList.value[selectedUserIndex.value];
      return `${user.customerName} (${user.contactPhone || '无电话'})`;
    }
    return '';
  });

  // 用户选择变化事件
  const onUserChange = (e) => {
    setSelectedUser(e.detail.value);
  };

  // 初始化日期时间选择器数据
  const initDateTimeRange = () => {
    const dates = [];
    const times = [];

    // 根据 dataInfo.reservationDays 限制提前预约天数
    const reservationDays = props.dataInfo.reservationDays || 0;
    const today = new Date();

    // 生成可预约的日期（从今天 + reservationDays 开始，往后30天）
    for (let i = reservationDays; i < reservationDays + 30; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      dates.push(`${date.getFullYear()}-${month}-${day}`);
    }

    // 生成时间段（9:00-18:00，每小时一个时间段）
    for (let hour = 9; hour <= 18; hour++) {
      times.push(`${String(hour).padStart(2, '0')}:00`);
    }

    dateTimeRange.value = [dates, times];
  };

  // 日期时间选择器变化事件
  const onDateTimeChange = (e) => {
    dateTimeIndex.value = e.detail.value;
    const selectedDate = dateTimeRange.value[0][e.detail.value[0]];
    const selectedTime = dateTimeRange.value[1][e.detail.value[1]];
    reservationForm.datetime = `${selectedDate} ${selectedTime}`;
  };

  // 计算是否可以确认预约
  const canConfirm = computed(() => {
    return reservationForm.customerId && reservationForm.datetime;
  });

  // 显示预约弹窗
  const showReservationModal = async () => {
    // #ifdef MP
    sheep.$platform
      .useProvider('wechat')
      .subscribeMessage(WxaSubscribeTemplate.ORDER_APPOINT_SUCCESS);
    // #endif
    // 获取用户列表
    await getUserList();

    if (userList.value.length === 0) {
      uni.showToast({
        title: '暂无可选择的客户',
        icon: 'none'
      });
      return;
    }

    isReservationModalVisible.value = true;
  };

  // 隐藏预约弹窗
  const hideReservationModal = () => {
    isReservationModalVisible.value = false;
    // 重置表单
    selectedUserIndex.value = 0;
    reservationForm.customerId = '';
    reservationForm.customerName = '';
    reservationForm.contactPhone = '';
    reservationForm.datetime = '';
    reservationForm.remark = '';
    dateTimeIndex.value = [0, 0];
  };

  // 确认预约
  const confirmReservation = () => {
    if (!canConfirm.value) {
      uni.showToast({
        title: '请填写完整的预约信息',
        icon: 'none'
      });
      return;
    }

    // 触发预约确认事件
    emit('reservation-confirm', {
      ...reservationForm,
      orderId: props.dataInfo.id || ''
    });
    hideReservationModal();
  };

  const getReservationStatusText = (status) => {
    const map = {
      PENDING: "已预约",
      IN_PRODUCTION: "待处理",
      COMPLETED: "已完成",
      CANCELLED: "已取消"
    };
    return map[status] || "未知状态";
  };

  const skuString = computed(() => {
    if (!props.skuText) {
      return '';
    }
    if (typeof props.skuText === 'object') {
      return props.skuText.join(',');
    }
    return props.skuText;
  });

  // 组件挂载时初始化数据
  onMounted(() => {
    initDateTimeRange();
  });
</script>

<style lang="scss" scoped>
  .order-state{
    color: #faad14;
  }
  .reservation-status-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 10rpx;
  }
  .tool-btn {
    width: 160rpx;
    height: 60rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }
  .point-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .ss-order-card-warp {
    padding: 20rpx;

    .img-box {
      width: 164rpx;
      height: 164rpx;
      border-radius: 10rpx;
      overflow: hidden;

      .order-img {
        width: 164rpx;
        height: 164rpx;
      }
    }

    .box-right {
      flex: 1;
      position: relative;

      .tool-box {
        position: absolute;
        right: 0rpx;
        bottom: -10rpx;
      }
    }

    .title-text {
      font-size: 28rpx;
      font-weight: 500;
      line-height: 40rpx;
    }

    .spec-text {
      font-size: 24rpx;
      font-weight: 400;
      color: $dark-9;
      min-width: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }

    .price-text {
      font-size: 24rpx;
      font-weight: 500;
      font-family: OPPOSANS;
    }

    .total-text {
      font-size: 24rpx;
      font-weight: 400;
      line-height: 24rpx;
      color: $dark-9;
      margin-left: 8rpx;
    }
  }

  /* 预约弹窗样式 */
  .reservation-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    align-items: flex-end;
  }

  .reservation-modal {
    width: 100%;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    animation: slideUp 0.3s ease-out;
  }

  @keyframes slideUp {
    from {
      transform: translateY(100%);
    }
    to {
      transform: translateY(0);
    }
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 40rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }

  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }

  .modal-close {
    font-size: 40rpx;
    color: #999;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .modal-content {
    padding: 40rpx;
  }

  .form-item {
    margin-bottom: 40rpx;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: 500;
  }

  .form-input {
    width: 100%;
    height: 80rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
  }

  .form-picker {
    width: 100%;
  }

  .picker-display {
    display: flex;
    align-items: center;
    color: #333;

    &:empty::before {
      content: '请选择';
      color: #999;
    }
  }

  .form-textarea {
    width: 100%;
    min-height: 120rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 10rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
    resize: none;
  }

  .modal-footer {
    display: flex;
    padding: 20rpx 40rpx 40rpx;
    gap: 20rpx;
  }

  .cancel-btn, .confirm-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cancel-btn {
    background-color: #f5f5f5;
    color: #666;
  }

  .confirm-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;

    &:disabled {
      background: #ccc;
      color: #999;
    }
  }
</style>

